package com.study.cloud.gateway.common.rule;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 动态服务缓存管理类
 * @author wangwancheng
 * @create 2025/7/19 14:10
 */
public class DynamicConfigManager {
    /**
     * 服务定义集合 uniqueId:服务唯一标识
     */
    private ConcurrentHashMap<String/**uniqueId**/, ServiceDefinition> serviceDefinitionMap = new ConcurrentHashMap<>();

    /**
     * 服务实例集合
     */
    private ConcurrentHashMap<String/**uniqueId**/, Set<ServiceInstance>> serviceInstanceMap = new ConcurrentHashMap<>();
    /**
     * 规则集合
     {
          "rules":[
                 "id":"1",
                 "name":"http-server",
                 "protocol":"http",
                 "serviceId":"backend-http-server",
                 "prefix":"/user",
                 "paths":[
                    "/http-server/ping"
                 ],
                 "filterConfigs":[
                    "id":"load_balancer_filter",
                    "config":{
                        "load_balancer":"RoundRobin"
                    }
                 ]
            ]
      }
     */
    private ConcurrentHashMap<String/**ruleId**/,Rule> ruleMap = new ConcurrentHashMap<>();
    //路径 及 规则 的集合
    private ConcurrentHashMap<String/**path**/,Rule> pathRuleMap = new ConcurrentHashMap<>();
    private ConcurrentHashMap<String/**serviceName**/,List<Rule>> serviceRuleMap = new ConcurrentHashMap<>();
    /**
     * 单例模式
     */
    private DynamicConfigManager() {
    }


    private static class SingletonHolder {
        private static final DynamicConfigManager INSTANCE = new DynamicConfigManager();
    }
    public static DynamicConfigManager getInstance() {
        return SingletonHolder.INSTANCE;
    }

    /** 对服务定义缓存进行操作方法*/
    /**
     * 添加服务定义
     * @param uniqueId
     * @param serviceDefinition
     */
    public void addServiceDefinition(String uniqueId,ServiceDefinition serviceDefinition) {
        serviceDefinitionMap.put(uniqueId,serviceDefinition);
    }
    /**
     * 删除服务定义
     * @param uniqueId
     */
    public void removeServiceDefinition(String uniqueId) {
        serviceDefinitionMap.remove(uniqueId);
    }
    /**
     * 获取服务定义
     * @param uniqueId
     * @return
     */
    public ServiceDefinition getServiceDefinition(String uniqueId) {

        return serviceDefinitionMap.get(uniqueId);
    }
    /**
     * 获取所有服务定义
     * @return
     */
    public ConcurrentHashMap<String, ServiceDefinition>  getServiceDefinitionMap() {
        return serviceDefinitionMap;
    }

    /******对服务实例缓存的操作*******/
    /**
     * 添加单个服务实例
     * @param uniqueId
     * @param serviceInstance
     */
    public void addServiceInstance(String uniqueId,ServiceInstance serviceInstance) {
        Set<ServiceInstance> set = serviceInstanceMap.get(uniqueId);
        set.add(serviceInstance);
    }

    /**
     * 添加多个实例
     * @param uniqueId
     * @param serviceInstances
     */
    public void addServiceInstance(String uniqueId,Set<ServiceInstance> serviceInstances) {
        serviceInstanceMap.put(uniqueId, serviceInstances);
    }

    /**
     * 更新服务实例
     * @param uniqueId
     * @return
     */
    public void updateServiceInstance(String uniqueId,ServiceInstance serviceInstance) {
        Set<ServiceInstance> set = removeServiceInstance(uniqueId, serviceInstance);
        set.add(serviceInstance);
    }
    /**
     * 删除服务实例
     * @param uniqueId
     * @param serviceInstance
     */
    public Set<ServiceInstance> removeServiceInstance(String uniqueId,ServiceInstance serviceInstance) {
        Set<ServiceInstance> set = serviceInstanceMap.get(uniqueId);
        Iterator<ServiceInstance> iterator = set.iterator();
        while (iterator.hasNext()){
            ServiceInstance instance = iterator.next();
            if (instance.getServiceInstanceId().equals(serviceInstance.getServiceInstanceId())){
                iterator.remove();
                break;
            }
        }
        return set;
    }
    public void removeServiceInstance(String uniqueId) {
        serviceInstanceMap.remove(uniqueId);
    }
    /**
     * 获取服务实例列表
     * @param uniqueId
     * @return
     */
    public Set<ServiceInstance> getServiceInstances(String uniqueId) {
        return serviceInstanceMap.get(uniqueId);
    }

    /**********对规则缓存的操作*************/
    /**
     * t添加单个规则
     */
   /* public void addRule(String ruleId,Rule rule) {
        ruleMap.put(ruleId,rule);
    }*/
    /**
     * 添加多个规则
     */
    public void addRules(List<Rule> ruleList) {
        ConcurrentHashMap<String,Rule> newRuleMap = new ConcurrentHashMap<>();
        ConcurrentHashMap<String,Rule> newPathRuleMap = new ConcurrentHashMap<>();
        ConcurrentHashMap<String,List<Rule>> newServiceMap = new ConcurrentHashMap<>();
        for (Rule rule : ruleList){
            newRuleMap.put(rule.getId(),rule);
            List<Rule> rules = newServiceMap.get(rule.getServerId());
            if (rules == null){
                rules = new ArrayList<>();
            }
            rules.add(rule);
            newServiceMap.put(rule.getServerId(),rules);
            for (String path : rule.getPaths()){
                String key = rule.getServerId()+"."+path;
                newPathRuleMap.put(key,rule);
            }
        }
        ruleMap = newRuleMap;
        serviceRuleMap = newServiceMap;
        pathRuleMap = newPathRuleMap;

    }
    /**
     * 删除单个规则
     */
    public void removeRule(String ruleId) {
        ruleMap.remove(ruleId);
    }
    /**
     * 删除多个规则
     */
    public void removeRules(List<Rule> rules) {

    }
    /**
     * 获取所有规则
     */
    public ConcurrentHashMap<String, Rule> getRules() {
        return ruleMap;
    }
    /**
     * 获取指定id的规则
     */
    public Rule getRule(String ruleId) {
        return ruleMap.get(ruleId);
    }

    public Rule getRuleByPath(String path) {
        return pathRuleMap.get(path);
    }

    public List<Rule> getRuleByServiceId(String serviceId) {
        return serviceRuleMap.get(serviceId);
    }

}
